package at.evonfc.bl;

import java.util.Calendar;

public class DateUtils {
	private static DateUtils theInstance;
	
	private DateUtils() {
		
	}
	
	public static DateUtils getInstance() {
		if(theInstance == null) {
			theInstance = new DateUtils();
		}
		return theInstance;
	}
	
	public String convertToDateString(Calendar c) {
		if(c == null) {
			return "n/a";
		}
		return c.get(Calendar.DAY_OF_MONTH)+"."+(c.get(Calendar.MONTH)+1)+"."+c.get(Calendar.YEAR);
	}

	public String convertToDateString(int day, int month, int year) {
		return day+"."+(month+1)+"."+year;
	}
	
	public String convertToTimeString(Calendar c) {
		if(c == null) {
			return "";
		}
		return String.format("%02d", c.get(Calendar.HOUR_OF_DAY)) + ":" +String.format("%02d", c.get(Calendar.MINUTE));
	}
	
	public String convertToTimeString(int hour, int minute) {
		return String.format("%02d", hour) + ":" +String.format("%02d", minute);
	}
	
	public String mergeDateAndTime(String dateString, String timeString) {
		return dateString+":"+timeString;
	}
	
	public String convertToDatabaseString(String dateAndTime) {
		return dateAndTime.split("\\.")[0]+":"+dateAndTime.split("\\.")[1]+":"+dateAndTime.split("\\.")[2];
	}
	
	public String convertToDatabaseString(Calendar c) {
		return c.get(Calendar.DAY_OF_MONTH)+":"+(c.get(Calendar.MONTH)+1)+":"+c.get(Calendar.YEAR) + ":" + String.format("%02d", c.get(Calendar.HOUR_OF_DAY))+":"+String.format("%02d", c.get(Calendar.MINUTE));
	}
	
	public Calendar convertToCalendar(String date) {
		String[] dateParts = date.split(":");
		Calendar cal = Calendar.getInstance();
		
		for(int i = 0; i < dateParts.length; i++) {
			int digit = Integer.parseInt(dateParts[i].trim());
			switch(i) {
			case 0: cal.set(Calendar.DAY_OF_MONTH, digit); break;
			case 1: cal.set(Calendar.MONTH, digit); cal.add(Calendar.MONTH, -1); break;
			case 2: cal.set(Calendar.YEAR, digit); break;
			case 3: cal.set(Calendar.HOUR_OF_DAY, digit); break;
			case 4: cal.set(Calendar.MINUTE, digit); break;
			}
		}
		
		return cal;
	}
}
